package com.uphone.mvpdemo.base;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.radish.baselibrary.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.uphone.mvpdemo.MyApp;
import com.uphone.mvpdemo.R;
import com.uphone.mvpdemo.http.ApiService;
import com.uphone.mvpdemo.http.FailureConsumer;
import com.uphone.mvpdemo.http.RxSchedulers;
import com.uphone.mvpdemo.http.SuccessfulConsumer;
import com.uphone.mvpdemo.util.CommonUtil;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import okhttp3.ResponseBody;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/4/17
 *     desc   :
 * </pre>
 */
public abstract class BaseListActivity<D, A extends BaseQuickAdapter> extends BaseGActivity {
    @BindView(R.id.recyclerView)
    protected RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    protected SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll)
    protected LinearLayout ll;
    protected A mAdapter;
    protected int page = 1;
    @BindView(R.id.tv_empty)
    protected TextView tvEmpty;
    @BindView(R.id.rl_recycler)
    protected RelativeLayout rlRecycler;
    private boolean isEnableLoadMore = true;
    protected boolean isDividerLine = true;
    private boolean isShowLoading = true;

    public void setShowLoading(boolean showLoading) {
        isShowLoading = showLoading;
    }

    @Override
    protected int initLayout() {
        return R.layout.layout_base_list;
    }

    @Override
    protected void initView() {
        if (isDividerLine) {
            recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        }
        RecyclerView.LayoutManager layoutManager = getLayoutManager();
        if (layoutManager == null)
            layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter = initAdapter();
        recyclerView.setAdapter(mAdapter);
    }

    protected RecyclerView.LayoutManager getLayoutManager() {
        return null;
    }

    @Override
    protected void initListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                itemClick(mAdapter, view, position);
            }
        });


        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                itemChildClick(mAdapter, view, position);
            }
        });

        CommonUtil.initRefresh(this, refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(1);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                loadData(++page);
            }
        });
    }


    protected void itemChildClick(A adapter, View view, int position) {

    }

    protected void setEnableLoadMore(boolean isEnableLoadMore) {
        refreshLayout.setEnableLoadMore(isEnableLoadMore);
        this.isEnableLoadMore = isEnableLoadMore;
    }

    protected void loadData(final int page) {
        this.page = page;
        ApiService apiService = MyApp.apiService(ApiService.class);
        Observable<ResponseBody> loadData = loadData(apiService);
        if (loadData == null)
            return;
        loadData.compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    if (isShowLoading)
                        showLoading();
                })
                .doFinally(() -> {
                    if (isShowLoading)
                        closeLoading();
                    if (refreshLayout != null) {
                        refreshLayout.finishRefresh();//传入false表示刷新失败
                        refreshLayout.finishLoadMore();//传入false表示加载失败
                    }
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        List<D> list = getDataList(jsonObject);
                        if (list == null || list.size() == 0) {
                            if (page == 1) {
                                rlRecycler.setVisibility(View.GONE);
                            } else {
                                ToastUtil.showShort("暂无更多数据");
                                if (refreshLayout != null && isEnableLoadMore) {
                                    refreshLayout.setEnableLoadMore(false);//传入false表示加载失败
                                }
                                BaseListActivity.this.page--;
                            }
                            return;
                        }
                        if (refreshLayout != null && isEnableLoadMore) {
                            refreshLayout.setEnableLoadMore(isEnableLoadMore);//传入false表示加载失败
                        }
                        rlRecycler.setVisibility(View.VISIBLE);
                        if (page == 1) {
                            mAdapter.setNewData(list);
                        } else {
                            mAdapter.addData(list);
                        }
                    }
                }, new FailureConsumer());
    }

    protected abstract Observable<ResponseBody> loadData(ApiService apiService);

    protected abstract List<D> getDataList(String json);

    protected abstract void itemClick(A adapter, View view, int position);

    /**
     * 初始化适配器
     *
     * @return
     */
    protected abstract A initAdapter();

    @Override
    protected void initData() {
        loadData(1);
    }

}
